package cn.tsmchina.one.dao.user;

import java.util.List;

import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import cn.tsmchina.one.dao.BaseDaoSupport;
import cn.tsmchina.one.domain.user.User;
import cn.tsmchina.one.util.C;

/**
 * Description:
 * @author ying 
 * @date 2013-10-4
 * @version 1.0
 * Copyright: Copyright (c) 2013 TSM,Inc
 */
@Repository
public class UserDaoImpl extends BaseDaoSupport<User> implements UserDao {
	@Override
	public Long addUser(User user)
	{
		return (Long)super.add(user);
	}

	@Override
	//用户是否存在
	public User getUserByPhone(String phone, long customerId) {
		String hql = "from User u where u.phone='"+phone+"' and u.delflag ='0' and customerId=? order by u.createDate desc";
		return (User) find(hql, new Object[]{customerId});
	}
	
	@Override
	public User getUserById(String id) {
		String hql = "from User u where u.id='"+id+"' and u.delflag ='0'";
		return (User) find(hql);
	}
	
	@Override
	//登录验证
	public User getUser(String phone, String password, long customerId) {
		String hql = "from User u where u.phone='"+phone+"' and password = '"+password +"' and u.delflag ='0' and customerId=?";
		return (User) find(hql, new Object[]{customerId});
	}
	
	@Override
	public int updateUser(User user) {
		Long userId = user.getId();
		String phone = user.getPhone();
		String address = user.getAddress();
		if(address==null)
			address="";
		String realName = user.getRealName();
		if(realName==null)
			realName="";
		Short gender = user.getGender();
		String birthday = user.getBirthday();
		
		String hql = "update from User u set u.phone = '"+phone+"',u.address = '"+address+"'," +
				"u.realName = '"+realName+"', u.gender = '"+gender+"', u.birthday = '"+birthday+"' where u.id = '"+userId+"'";
		
		return exexuteUpdate(hql);
	}
	
	@Override
	public int updateUserPass(User user) {
		Long userId = user.getId();
		String password = user.getPassword();
		
		String hql = "update from User u set u.password = '"+password+"' where u.id = '"+userId+"'";
		return exexuteUpdate(hql);
	}

	@Override
	public List<User> getUserListByIds(String uids,int page, long customerId) {
		if(!StringUtils.isEmpty(uids)){
			String hql = "from User u where u.id in ("+uids+") and u.delflag ='0' and u.customerId=?";
			return (List<User>) lists(hql,page,C.Paging.SIZE, new Object[]{customerId});
		}
		
		return null;
	}

	@Override
	public int getUserTotalByIds(String uids, long customerId) {
		String hql = "select count(*) from User u where u.id in ("+uids+") and u.delflag ='0' and u.customerId=?";
		return count(hql, customerId);
	}
	
}

